//
//  NetworkTools.swift
//  ZTWeiboo
//
//  Created by mac on 15/8/14.
//  Copyright © 2015年 YYL. All rights reserved.
//

import UIKit
import AFNetworking

class NetworkTools: AFHTTPSessionManager {
    static let shareTools : NetworkTools = {
        let baseUrl = NSURL(string: "https://api.weibo.com/")
        
        let tools = NetworkTools(baseURL: baseUrl)
        
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
    }()
    
    private let clientId = "2300223879"
    private let appSecret = "28adf48dd282b42d6581df5ec2d91562"
    
    let redirectUri = "http://baidu.com"
    
    func oauthUrl() -> NSURL{
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        return NSURL(string: urlString)!
    }
    
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?, error: NSError?)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        
        POST(urlString, parameters: params, success: { (_, JSON) -> Void in
            finished(result: JSON as? [String: AnyObject], error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }

    }
}